#pragma once
#include <iostream>
#include <unordered_map>
#include <string>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <sys/types.h>
#include "InetAddr.hpp"
#include "Log.hpp"
using namespace LogModule;
class Route
{
public:
    Route() {};
    void MessageRoute(int socket_fd, const std::string &msg, InetAddr &addr)
    {
        if (is_user_exist(addr) == false)
        {
            add_user(addr); // 添加用户
            std::cout << addr.Ip() << ":" << addr.Port() << " 上线了" << std::endl;
        }

        std::string sendmsg = "[" + addr.String_Addr() + "]" + " : " + msg;
        for (auto &user : _userlist)
        {
            struct sockaddr_in user_addr = user.GetAddr();
            sendto(socket_fd, sendmsg.c_str(), sendmsg.size(), 0, (const struct sockaddr *)&(user_addr), sizeof(user.GetAddr()));
        }
        // 此时这个用户已经存在了
        if (msg == "东北雨姐和崔庆斐") // 退出密码
        {
            delete_user(addr);
        }
    }
    ~Route() {};

private:
    void delete_user(InetAddr &addr)
    {
        for (auto it = _userlist.begin(); it != _userlist.end(); ++it)
        {
            if (*it == addr)
            {
                LOG(LogLevel::INFO) << "delete user:" << addr.String_Addr();
                _userlist.erase(it);
                std::cout << addr.Ip() << ":" << addr.Port() << " 下线了" << std::endl;
                return;
            }
        }
    }
    bool is_user_exist(InetAddr &addr)
    {
        for (auto &user : _userlist)
        {
            if (user == addr)
                return true;
        }
        return false;
    }
    void add_user(InetAddr &addr)
    {
        LOG(LogLevel::INFO) << "add user:" << addr.String_Addr();
        _userlist.push_back(addr);
    }
    // 首次发消息，记录用户信息 等同于登录
    std::vector<InetAddr> _userlist; // 在线用户列表
};